/**
 * 通过朋友圈分享进入小程序
 */
import store from "../store";
import {
	wxappAuth,
	getUser,
	getTouristLogin
} from "@/api/user";
import dayjs from "dayjs";
import cookie from "@/utils/store/cookie.js";
export const pyqLogin = (option) => {
	return new Promise((resolve, reject) => {
		let scenes = wx.getLaunchOptionsSync().scene;
		if (scenes == 1154) {
			// 朋友圈内打开“单页模式”
			// 如果获取登录凭证失败，添加token及用户信息供游客访问相关页面的接口
			getTouristLogin()
				.then((res) => {
					if (res.data) {
						let token = res.data.token;
						store.commit("LOGIN", token, dayjs(res.data.expires_time));
						let userInfo = {
							uid: "",
							mcCode: res.data.mc_code
						}
						store.dispatch('changeUserInfo', {
							user: userInfo
						})
						resolve(userInfo);
					}
				});
		} else {
			wx.login({
				success: res => {
					let code = res.code;
					store.commit("UPDATE_WXCODE", res.code);
					if (code) {
						wxappAuth({
							code: code,
							spread: option.spread,
							taskId: option.rewardId
						}).then(({
							data
						}) => {
							store.commit('setIsMock', data.isMock)
							store.commit("LOGIN", data.token, dayjs(data.expires_time));
							store.commit("SET_SUB_MSG_TEMPLATES", data.subMsg);
							getUser().then(user => {
								if(option.rewardId && option.spread != user.data.uid){
									uni.redirectTo({
										url:'/pages/user/invite/receive?id=' + option.rewardId
									})
								}
								resolve(user.data)
								store.dispatch('changeUserInfo', {
									user: user.data
								})
							}).catch(err => {
								reject()
								uni.reLaunch({
									url: "/pages/poorNetwork/main"
								})
							});
						}).catch(error => {
							reject()
							uni.reLaunch({
								url: "/pages/poorNetwork/main"
							})
						});
					} else {
						reject()
						uni.reLaunch({
							url: "/pages/poorNetwork/main"
						})
					}
				},
				fail: error => {
					reject()
					uni.reLaunch({
						url: "/pages/poorNetwork/main"
					})
				}
			});
		}
	})
}
